import { useState, useEffect } from 'react';
import { useParams } from 'react-router-dom';
import api from './api';
import type { Snippet } from './snippetTypes';

function SnippetDetail() {
  const { id } = useParams<{ id: string }>();
  const [snippet, setSnippet] = useState<Snippet | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const fetchSnippet = async () => {
      try {
        // ✅ 添加 /api 前缀，匹配后端接口路径
        const response = await api.get<Snippet>(`/snippets/${id}`); 
        setSnippet(response.data);
        setLoading(false);
      } catch (error) {
        console.error('获取代码失败:', error);
        setLoading(false);
      }
    };
    fetchSnippet();
  }, [id]);

  if (loading) return <div>加载中...</div>;
  if (!snippet) return <div>代码片段不存在</div>;

  return (
    <div className="snippet-detail">
      <h2>{snippet.title}</h2>
      <pre>{snippet.code}</pre>
    </div>
  );
}

export default SnippetDetail;